package cn.com.dycc.common.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import cn.com.dycc.common.http.BodyReaderHttpServletRequestWrapper;
import cn.com.dycc.common.http.HttpHelper;
import cn.com.dycc.util.StringUtil;

/**
 * 敏感字符过滤器
 * @author gaofan
 *
 */
public class InvalidCharFilter implements Filter{
	
	public void destroy() {
		
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest)arg0;
		
		try{
			
			if (request.getCharacterEncoding() == null) {  
				request.setCharacterEncoding("UTF-8");  
	        }
			String agent = request.getHeader("user-agent");						
			String uri = request.getRequestURI();
			System.out.println("访问url:"+uri);
			String path = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
			//pc端
			if("/upbase".equals(path)){
				arg2.doFilter(arg0, arg1);
				return;
			}
			System.out.println("ContentType:"+request.getContentType());
			
			if("application/json".equals(request.getContentType())){
				System.out.println("打桩111111111111111");
				ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
				System.out.println("requestWrapper:"+HttpHelper.getBodyString(requestWrapper));
				arg2.doFilter(requestWrapper, arg1);
				return;		
			}
			Class clazz = request.getClass();  
	        Field requestField = clazz.getDeclaredField("request");  
	        requestField.setAccessible(true);  
	        Object innerRequest = requestField.get(request);//获取到request对象  
	        //设置尚未初始化 (否则在获取一些参数的时候，可能会导致不一致)  
	        Field field = innerRequest.getClass().getDeclaredField("parametersParsed");  
	        field.setAccessible(true);  
	        field.setBoolean(innerRequest , false);  
	        Field coyoteRequestField = innerRequest.getClass().getDeclaredField("coyoteRequest");  
	        coyoteRequestField.setAccessible(true);  
	        Object coyoteRequestObject = coyoteRequestField.get(innerRequest);//获取到coyoteRequest对象  
	        Field parametersField = coyoteRequestObject.getClass().getDeclaredField("parameters");  
	        parametersField.setAccessible(true);  
	        Object parameterObject = parametersField.get(coyoteRequestObject);//获取到parameter的对象 
	        //获取hashtable来完成对参数变量的修改  
	        Field hashTabArrField = parameterObject.getClass().getDeclaredField("paramHashValues");  
	        hashTabArrField.setAccessible(true);  
	        @SuppressWarnings("unchecked")  
	        Map<String,ArrayList<String>> map = (Map<String,ArrayList<String>>)hashTabArrField.get(parameterObject);  
	        System.out.println("替换前:"+map);
	        System.out.println("打桩2222222222222222222222222");
	        Enumeration<String>paramNames=request.getParameterNames();
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				System.out.println("paramName:"+paramName);
				ArrayList<String> list=map.get(paramName);
				ArrayList<String> afterList=new ArrayList<String>();
				for(String str:list){
					System.out.println("paramNameValue"+str);
					afterList.add(StringUtil.filterContent(str));
				}
				map.put(paramName, afterList);
				
				
			}
			System.out.println("打桩1111111111111111111");
			System.out.println("替换后："+map);
			
			
		
		}catch(Exception e){
			e.printStackTrace();
		}
		arg2.doFilter(arg0, arg1);
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		
		
	}
	
	public static String getRequestJson(HttpServletRequest request) {
        boolean isGetRequest = request.getMethod().toLowerCase().equals("get");
        try {
            if (isGetRequest) {
                return new String(request.getQueryString().getBytes(
                        "ISO-8859-1"), "UTF-8").replaceAll("%22", "\"");
            }
            int contentLength = request.getContentLength();
            if (contentLength < 0) {
                return null;
            }
            byte buffer[] = new byte[contentLength];
            for (int i = 0; i < contentLength;) {

                int readlen = request.getInputStream().read(buffer, i,
                        contentLength - i);
                if (readlen == -1) {
                    break;
                }
                i += readlen;
            }
            return new String(buffer, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	
	public static String getPostByTextPlain(HttpServletRequest request) throws IOException{
		 
		BufferedReader reader = request.getReader();
        char[] buf = new char[512];
        int len = 0;
        StringBuffer contentBuffer = new StringBuffer();
        while ((len = reader.read(buf)) != -1) {
            contentBuffer.append(buf, 0, len);
        }
        String content= contentBuffer.toString();
        return content;
	}


	

}
